package com.heima.wemedia.interceptor;


import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 拦截器
 */
@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {

    /**
     * 添加用户ID
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取handler信息
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)){
            // 把用户ID存入ThreadLocal
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocal.setUser(wmUser);
        }
        return true;
    }

    /**
     * 清除用户数据
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocal.remove();
    }
}
